﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using AutoMapper;

namespace UserGroupData
{
    public class MeetingRepository : IMeetingRepository 
    {
        public MeetingDTO GetMeeting(int id)
        {
            using (var ctx = new UserGroupEntities())
            {
                var meeting = ctx.Meetings.Where(d => d.Id == id);
                var entity = meeting.FirstOrDefault();
                Mapper.CreateMap<Meeting, MeetingDTO>();
                var dto = Mapper.Map<Meeting, MeetingDTO>(entity);
                return dto;
            }
        }

        public List<MeetingDTO> GetAllMeetings()
        {
            using (var ctx = new UserGroupEntities())
            {
                var entities = ctx.Meetings.ToList();
                Mapper.CreateMap<Meeting, MeetingDTO>();
                var dto = Mapper.Map<List<Meeting>, List<MeetingDTO>>(entities);
                return dto;
            }
        }

        public int AddNewMeeting(MeetingDTO dto)
        {
            using (var ctx = new UserGroupEntities())
            {
                Mapper.CreateMap<MeetingDTO, Meeting>();
                var entity = Mapper.Map<MeetingDTO, Meeting>(dto);
                ctx.AddToMeetings(entity);
                ctx.SaveChanges();
                return entity.Id;

            }
        }

        public void UpdateMeeting(MeetingDTO dto)
        {
            using (var ctx = new UserGroupEntities())
            {
                Mapper.CreateMap<MeetingDTO, Meeting>();
                var entity = Mapper.Map<MeetingDTO, Meeting>(dto);
                ctx.ApplyCurrentValues("Meetings", entity);
                ctx.SaveChanges();
            }
        }

        public void DeleteMeetingDTO(int id)
        {
            using (var ctx = new UserGroupEntities())
            {
                Meeting dbDept = ctx.Meetings.First(d => d.Id == id);
                ctx.DeleteObject(dbDept);
                ctx.SaveChanges();
            }
        }
    }
}
